package com.myeasyexcel.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import org.springframework.beans.factory.annotation.Autowired;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.lang.reflect.Field;

import java.util.Set;


public class EasyExcelValiHelper {

    private EasyExcelValiHelper(){}
    @Autowired
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    static {
        try {
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            validator = factory.getValidator();
        } catch (Exception e) {
            throw new RuntimeException("Failed to initialize Validator", e);
        }
    }
    public static <T> String validateEntity(T obj) throws NoSuchFieldException {
        StringBuilder result = new StringBuilder();
        if(!isAllFieldNull(obj)) {
            Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
            int i = 1;
            if (set != null && !set.isEmpty()) {
                // 不符合规则
                for (ConstraintViolation<T> cv : set) {
                    Field declaredField = obj.getClass().getDeclaredField(cv.getPropertyPath().toString());
                    ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);
                    result.append(i++).append(".").append(annotation.value()[0]).append(cv.getMessage()).append(";\n");
                }
            }
        }
        return result.toString();
    }

    /***
     * 判断对象所有属性是否为空
     *
     * @param obj 对象
     * @return boolean 所有都是null返回true
     * @throws Exception
     */
    private static boolean isAllFieldNull(Object obj) {
        Class<?> clazz = obj.getClass();
        //得到属性集合
        Field[] fs = clazz.getDeclaredFields();
        boolean flag = true;
        //遍历属性
        for (Field field : fs) {
            try {
                // 设置属性是可以访问的(私有的也可以)
                field.setAccessible(true);
                // 得到此属性的值
                Object val = field.get(obj);
                // 只要有1个属性不为空,那么就不是所有的属性值都为空
                if (val != null) {
                    flag = false;
                    break;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }


}